package com.greyshark.bledemo.base

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding

abstract class SimpleDiffAdapter<T, VB : ViewBinding>(
    // 移除 data 参数，改用 AsyncListDiffer 管理数据
    open val inflater: (
        LayoutInflater,
        parent: ViewGroup,
        attachToRoot: Boolean
    ) -> VB
) : RecyclerView.Adapter<SimpleDiffAdapter.ViewHolder<VB>>() {

    // 定义 DiffUtil.ItemCallback 作为抽象属性，由子类实现
    abstract val diffCallback: DiffUtil.ItemCallback<T>

    // 初始化 AsyncListDiffer
    private val differ = AsyncListDiffer(this, diffCallback)

    // ViewHolder 保持不变
    class ViewHolder<VB : ViewBinding>(val t: VB) : RecyclerView.ViewHolder(t.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<VB> {
        return ViewHolder(inflater(LayoutInflater.from(parent.context), parent, false))
    }

    override fun onBindViewHolder(holder: ViewHolder<VB>, position: Int) {
        // 使用 differ.currentList 获取数据
        onBindData(holder.t, differ.currentList[position], position)
    }

    override fun getItemCount(): Int {
        return differ.currentList.size
    }

    // 提交新列表，可选排序
    open fun submitList(newList: List<T>) {
        differ.submitList(newList)
    }

    // 获取当前列表
    fun getCurrentList(): List<T> = differ.currentList

    protected abstract fun onBindData(binding: VB?, t: T, position: Int)

    override fun getItemViewType(position: Int): Int = 0
}